package net.monare.mifss.admin.ui;

import net.monare.mifss.MifssAdminMainUI;
import net.monare.mifss.MifssMessages;
import net.monare.mifss.evn.LoginFormListener;

import net.monare.mifss.lib.AppContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.vaadin.server.Resource;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Image;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class LoginForm extends VerticalLayout {

	private static final long serialVersionUID = -8056116949003360113L;

    @Autowired
    private transient ApplicationContext applicationContext;

	private TextField txtLogin;
	private PasswordField txtPassword;
	private NativeButton btnLogin;

	public LoginForm() {

		String userNameLabel = MifssMessages.getMessage("label.user.name");
		String passwordLabel = MifssMessages.getMessage("label.password");
		String loginButtonText = MifssMessages.getMessage("button.login");

		this.txtLogin = new TextField(userNameLabel);
        this.txtLogin.setValue("admin");
		this.txtPassword = new PasswordField(passwordLabel);
        this.txtPassword.setValue("password");
		this.btnLogin = new NativeButton(loginButtonText);

		setSpacing(true);

		// add spacer label on top
		Label sz = new Label("");
		sz.setWidth(null);
		sz.setHeight("60px");
		addComponent(sz);

		//

		Resource res = new ThemeResource("img/mifss_logo.png");

		Image image = new Image(null, res);
		addComponent(image);
		setComponentAlignment(image, Alignment.MIDDLE_CENTER);

		Panel panel = new Panel();
		panel.setSizeUndefined(); // Shrink to fit content

		addComponent(panel);
		setComponentAlignment(panel, Alignment.MIDDLE_CENTER);

		// Create the content
		FormLayout content = new FormLayout();
		content.addComponent(txtLogin);
		content.addComponent(txtPassword);
		content.addComponent(btnLogin);
		content.setSizeUndefined(); // Shrink to fit
		content.setMargin(true);
		panel.setContent(content);

		LoginFormListener loginFormListener = getLoginFormListener();
		btnLogin.addClickListener(loginFormListener);

	}

	public LoginFormListener getLoginFormListener() {

		MifssAdminMainUI ui = (MifssAdminMainUI) UI.getCurrent();
		ApplicationContext context = AppContext.getApplicationContext();
		return context.getBean(LoginFormListener.class);

	}

	public TextField getTxtLogin() {
		return txtLogin;
	}

	public PasswordField getTxtPassword() {
		return txtPassword;
	}

}
